package com.code.generate;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: Generator
 * @Description: 生成器
 * @author simple
 * @date 2017年3月20日 上午11:01:10
 */
public class Generator {

	/**
	 * @Fields modelPath : 模板路径
	 */
	private String modelPath;
	/**
	 * @Fields outputPath : 生成路径
	 */
	private String outputPath;

	/**
	 * @Fields variable : 变量
	 */
	private Map<String, String> variable = new HashMap<String, String>();

	/**
	 * @Fields fields : 字段属性
	 */
	private List<Field> fields = new ArrayList<Field>();

	public Generator(String modelPath, String outputPath, Map<String, String> variable, List<Field> fields) {
		this.modelPath = modelPath;
		this.outputPath = outputPath;
		this.variable.putAll(variable);
		this.fields.addAll(fields);
	}

	public void generator() {
		List<MyFile> allFile = FileOperator.getAllFile(new MyFile(new File(modelPath)));
		for (MyFile file : allFile) {
			String fileName = getFileName(file);
			if (fileName.contains(".svn")) {
				continue;
			}
			for (String name : FileOperator.getVariables(fileName, true)) {
				fileName = fileName.replaceAll(name.replace("{", "\\{").replace("}", "\\}"), variable.get(name));
			}
			String content = FileOperator.readFile(file);
			for (String name : FileOperator.getVariables(content, true)) {
				String t = variable.get(name);
				// System.out.println("11111:" + name);
				// System.out.println("t:" + t);
				// System.out.println("content:" + content);
				content = content.replaceAll(name.replace("{", "\\{").replace("}", "\\}"), t.replace("$", "\\$"));
			}
			FileOutputStream fos;
			try {
				File f = new File(fileName);
				if (!f.getParentFile().exists()) {
					f.getParentFile().mkdirs();
				}
				if (!f.exists()) {
					f.createNewFile();
				}
				fos = new FileOutputStream(f);
				Writer out = new OutputStreamWriter(fos, file.getEncoding());
				out.write(content);
				out.close();
				fos.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private String getFileName(MyFile file) {
		String newFilePath = file.getAbsolutePath();
		newFilePath = newFilePath.replace(new File(modelPath).getAbsolutePath(), new File(outputPath).getAbsolutePath());
		return newFilePath;
	}
}
